package com.hqu.environment.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hqu.environment.constant.Constant;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;

/**
 * @Description: jwthelper,web令牌，对token进行封装和解封装，
 *
 * @Author: 邓勇嘉
 * @Date:2018/11/19 18:12
 * */
public class JwtHelper {

    //用来加密数字签名的密钥。
    private static final String  SECRET = "secret";
    //发布者 后面一块去校验
    private static final String  ISSUER = "dyj";


     /*
     * 用jwt工具为id生成token,为登录验证
     *
     * @param id 用户或管理员的id
     * @return token
     *
     * */
    public static String genToken(Integer id) {
        //签名算法
        Algorithm algorithm = null;
        try {
            algorithm = Algorithm.HMAC256(SECRET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        //当前时间
        Date now = new Date();
        //过期时间 3天
        Date expireTime = new Date(now.getTime() + Constant.THREE_DAY);

        JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER).withExpiresAt(expireTime);
        builder.withClaim("id", id);

        //填入信息 生成token
        return builder.sign(algorithm).toString();
    }


    /**
     * 校验token是否合法,并从中提取出id
     *
     * @param token
     * @return id 用户或管理员id
     */

    public static Integer verifyToken(String token){
        Algorithm algorithm = null;
        JWTVerifier verifier =null;
        DecodedJWT jwt=null;
        try {
            algorithm = Algorithm.HMAC256(SECRET);
            verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            jwt =  verifier.verify(token);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (JWTVerificationException exception){
            //抛出token校验错误异常
            throw new ApiException(ExceptionCode.USER_TOKEN_EXCEPTION);
        }
        //获取token中的id
        Map<String, Claim> map = jwt.getClaims();
        Integer id=map.get("id").asInt();
        return id;
    }

}